import React from 'react'
import {withRouter} from 'react-router'
import BaseComponent from 'basecomponent'
import classNames from 'classnames'
import icons from 'icons'
import Button from "button"
import Dropzone from 'react-dropzone'
import './style.scss'
import {Form, Select, Checkbox} from 'antd'
const FormItem = Form.Item
import api from 'apis'
const Option = Select.Option
import AntTable from 'anttable'
import appConfig from 'config'
import {USER_KEY} from 'auth'
import store from 'store'

class ReviseCompany extends BaseComponent {
  constructor() {
    super(...arguments)
    const location = this.props.location
    this.state = {
      companyID: location.query.Id ?  parseInt(location.query.Id) : 1,
      isRevise: location.state.revise ? location.state.revise : false,
      companyData: {},
      companyLogoImg: '',
      companyLogoPreview: '',
      showCheckbox: false,
      sightsData: [],
      checkSightsIndex: [],
      currentPage: 1,
      pageSize: 5,
      provinceData: [],
      cityData: [],
      JobData: [],
    }
    store.set('currentCompanyId', location.query.Id ? location.query.Id : 1)
  }

  componentDidMount() {
    const {companyID} = this.state
    this.getCompanyDetail(companyID)
    this.getJobList(companyID)
  }

  getCompanyDetail(id) {
    let companyId = id ? id : store.get('currentCompanyId')
    this.getCompanyDetailRP = api.company.getCompanyDetail(companyId)
    this.registerRequest(this.getCompanyDetailRP.request)
    this.getCompanyDetailRP.promise
      .then((res) => {
        res.Data && this.setState({companyData: res.Data})
        res.Data && this.mapCompanyData(res.Data)
      })
  }

  getJobList(id) {
    let companyId = id ? id : store.get('currentCompanyId')
    this.getJobListRP && this.getJobListRP.request.abort()
    this.getJobListRP = api.company.getJobList('', companyId)
    this.registerRequest(this.getJobListRP.request)
    this.getJobListRP.promise
      .then((res) => {
        res.Data && this.setState({JobData: res.Data})
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  topJob(text, record) {
    console.log(record)
    let jobData = {}
    if(record.Order && record.Order === 1){
      jobData = Object.assign({}, record, {Order: 0})
    }else{
      jobData = Object.assign({}, record, {Order: 1})
    }
    this.reviseJobRP && this.reviseJobRP.request.abort()
    this.reviseJobRP = api.company.reviseJob(jobData.Id, jobData)
    this.registerRequest(this.reviseJobRP.request)
    this.reviseJobRP.promise
      .then((res) => {
        alert('成功')
        this.getJobList(this.state.companyID)
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  watchJob(text, record) {
    this.props.router.push({
      pathname: 'home/revise/job',
      query: {Id: record.Id},
      state: {
        companyId: this.state.companyID,
        revise: false,
      }
    })
  }
  deleteJob(text, record) {
    this.deleteJobRP && this.deleteJobRP.request.abort()
    this.deleteJobRP = api.company.deleteJob(record.Id);
    this.registerRequest(this.deleteJobRP.request);
    this.deleteJobRP.promise
      .then((res)=>{
        alert('删除成功')
        let data = this.state.JobData
        this.state.JobData.forEach((item, index) => {
          if(item.Id === record.Id) {
            data.splice(index,1)
          }
        })
        this.setState({JobData: data})
      })
      .catch((err)=>{
        alert(err.msg)
      })
  }

  mapCompanyData(detail) {
    let tags = detail.Tags.split('  ')
    this.props.form.setFieldsValue({
      Name: detail.Name,
      Introduce: detail.Introduce,
      Tags: detail.Tags
    })
    this.getProvinceInfo(parseInt(detail.Area / 1000) * 1000, detail.Area)
    this.setState({
      companyLogoPreview: `${appConfig.apiHost}/File/?pid=${detail.Image}&key=${store.get(USER_KEY)}`,
      sightsData: detail.Pics ? detail.Pics.split('|').map((i) => {
        return {pic: i}
      }) : [],
    })
  }

  getProvinceInfo(Pid, Cid) {
    this.getProviceRP = api.address.getProvince()
    this.registerRequest(this.getProviceRP.request)
    this.getProviceRP.promise
      .then((res) => {
        res.Data && this.setState({provinceData: res.Data})
        res.Data && this.props.form.setFieldsValue({
          AddrP: Pid.toString(),
        })
        this.getCityInfo(Pid, Cid)
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  getCityInfo(Pid, Cid) {
    this.getCityRP && this.getCityRP.request.abort()
    this.getCityRP = api.address.getCity(Pid)
    this.registerRequest(this.getCityRP.request)
    this.getCityRP.promise
      .then((res) => {
        res.Data && this.setState({cityData: res.Data})
        res.Data && this.props.form.setFieldsValue({
          AddrP: Pid.toString(),
          AddrC: Cid.toString(),
        })
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  handleProvinceSelect(value, option) {
    if (value) {
      this.getCityRP && this.getCityRP.request.abort()
      this.getCityRP = api.address.getCity(value)
      this.registerRequest(this.getCityRP.request)
      this.getCityRP.promise
        .then((res) => {
          res.Data && this.setState({cityData: res.Data, defaultProvince: value})
          res.Data && this.props.form.setFieldsValue({
            AddrC: res.Data[0].Id.toString()
          })
        })
        .catch((err) => {
          alert(err.msg)
        })
    }

  }

  handleLogoFileSelect(files) {
    const {companyData} = this.state
    let file = files[0]
    if (file) {
      this.uploadLogoRP && this.uploadLogoRP.request.abort()
      this.uploadLogoRP = api.file.uploadFile(file)
      this.registerRequest(this.uploadLogoRP.request)
      this.uploadLogoRP.promise
        .then((res) => {
          this.setState({
            companyLogoImg: res.Data || '', companyData: Object.assign({},
              companyData, {Image: res.Data || ''})
          })
        })
        .catch((err) => {
          alert(err.msg)
        })
    }
  }

  handleSightsFileSelect(files) {
    let file = files[0]
    let list = this.state.sightsData
    if (file) {
      list.push(file)
      this.setState({sightsData: list})
    }
  }

  uploadSightsFiles(i) {
    const {sightsData} = this.state
    let index = i
    if (index > -1) {
      let postData = sightsData[index]
      if (postData instanceof File) {
        this.uploadRP && this.uploadRP.request.abort()
        this.uploadRP = api.file.uploadFile(postData)
        this.registerRequest(this.uploadRP.request)
        this.uploadRP.promise
          .then((res) => {
            sightsData[index] = {pic: res.Data}
            this.setState({sightsData: sightsData}, () => {
              if (index < sightsData.length) {
                this.uploadSightsFiles(index + 1)
              } else {
                this.uploadSightsFiles(-1)
              }
            })
          })
          .catch((err) => {
            if (index < sightsData.length) {
              this.uploadSightsFiles(index + 1)
            } else {
              this.uploadSightsFiles(-1)
            }
          })
      } else {
        if (index < sightsData.length) {
          this.uploadSightsFiles(index + 1)
        } else {
          this.uploadSightsFiles(-1)
        }
      }
    } else {
      this.uploadUniversityData()
    }
  }

  uploadUniversityData() {
    const {companyData, sightsData} = this.state
    let picStr = ''
    sightsData.length > 0 && sightsData.forEach(function (item, index) {
      if (index === 0 || index === sightsData.length) {
        picStr = picStr + item.pic
      } else {
        picStr = picStr + '|' + item.pic
      }
    })
    companyData.Pics = picStr
    this.reviseCompanyRP && this.reviseCompanyRP.request.abort()
    this.reviseCompanyRP = api.company.reviseCompany(companyData.Id, companyData)
    this.registerRequest(this.reviseCompanyRP.request)
    this.reviseCompanyRP.promise
      .then((res) => {
        res.Data && this.setState({companyData: res.Data})
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  handleSubmit(e) {
    e.preventDefault()
    const{provinceData,companyData} = this.state
    this.props.form.validateFields((err, values) => {
      if (!err) {
        companyData.Name = values.Name
        companyData.Area = values.AddrC ? values.AddrC : values.AddrP
        companyData.Introduce = values.Introduce
        companyData.Tags = values.Tags
        this.reviseCompanyRP && this.reviseCompanyRP.request.abort()
        this.reviseCompanyRP = api.company.reviseCompany(companyData.Id, companyData)
        this.registerRequest(this.reviseCompanyRP.request)
        this.reviseCompanyRP.promise
          .then((res) => {
            res.Data && this.setState({companyData: res.Data})
            alert('保存成功')
          })
          .catch((err) => {
            alert(err.msg)
          })
      }
    })
  }

  getLogoImgDiv() {
    const {companyLogoImg, companyLogoPreview} = this.state
    if (companyLogoPreview.length > 0) {
      return <img className={'preview-img'} src={companyLogoPreview}/>
    } else {
      if (companyLogoImg.length > 0) {
        return <img className={'preview-img'}
                    src={`${appConfig.apiHost}/File/?pid=${companyLogoImg}&key=${store.get(USER_KEY)}`}/>
      } else {
        return <div className={'default-wrapper'}>
          <img className={'image-default'} src={icons.uploadImg}/>
          <span>点击添加LOGO</span>
        </div>
      }
    }
  }

  render() {
    const {wrapperName, buttonWrapperName, clickBack, children} = this.props
    const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form
    const {
      companyData, sightsData, currentPage, pageSize, showCheckbox
      ,provinceData, JobData, cityData
    } = this.state

    const columns = [{
      title: '编号',
      dataIndex: 'Id',
      key: 'Id',
    }, {
      title: '岗位名称',
      dataIndex: 'Name',
      key: 'Name'
    },
      {
        title: '工作年限',
        dataIndex: 'Exp',
        key: 'Exp'
      },
      {
        title: '薪水',
        dataIndex: 'Salary',
        key: 'Salary',
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
             <a onClick={() => {
               this.topJob(text, record)
             }}>{record.Order && record.Order === 1 ? '取消置顶' : '置顶'}</a>
            <span className="ant-divider"/>
          <a onClick={() => {
            this.watchJob(text, record)
          }}>查看</a>
            <span className="ant-divider"/>
          <a onClick={()=>{this.deleteJob(text,record)}}>删除</a>
        </span>
        ),
      }]

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
      }),
    }

    const self = this
    return (
      children ? <div>{children}</div> :
        <div className={'sem-main-content'}>
          <div className={classNames('company-wrapper', wrapperName)}>
            <div className={classNames('button-wrapper', buttonWrapperName)}>
              <Button className={'back-button'} onClick={() => {
                  this.props.router.goBack()
              }}>{Button.AddOn({
                src: icons.backIcon, style: {
                  width: '1rem',
                  height: '1rem',
                  display: 'block',
                  backgroundRepeat: 'no-repeat',
                }
              })}</Button>
              <div className={'add-name'}>
                修改企业
              </div>
            </div>
            <Form onSubmit={this.handleSubmit.bind(this)} hideRequiredMark={true}>

              <div className={'body-top'}>
                <Dropzone className={'image-drop-zone'}
                          onDrop={this.handleLogoFileSelect.bind(this)}
                          accept={'image/*'}
                          multiple={false}>
                  {this.getLogoImgDiv()}
                </Dropzone>
                <div className={'body-top-middle'}>
                  <div className={'option-wrapper'}>
                    <div className={'option-title'}>公司名称</div>
                    <FormItem>
                      {getFieldDecorator('Name', {initialValue: companyData.Name})(
                        <input className={'option-input'}
                               type={'text'}/>
                      )}
                    </FormItem>
                  </div>
                  <div className={'option-wrapper'}>
                    <div className={'option-title'}>公司地址</div>
                    <FormItem>
                      {getFieldDecorator('AddrP')(
                        <Select className={'province-select'}
                                onSelect={this.handleProvinceSelect.bind(this)}
                                notFoundContent={'-'}>
                          {provinceData.map(function (item, index) {
                            return <Option key={item.Id.toString()} value={item.Id.toString()}>{item.Name}</Option>
                          })}
                        </Select>
                      )
                      }
                    </FormItem>
                    <FormItem>
                      {getFieldDecorator('AddrC')(
                        <Select className={'city-select'}
                                notFoundContent={'-'}
                                style={{marginLeft: '.25rem'}}
                        >
                          {
                            cityData && cityData.map(function (item, index) {
                              return <Option key={item.Id.toString()} value={item.Id.toString()}>{item.Name}</Option>
                            })
                          }
                        </Select>
                      )
                      }
                    </FormItem>
                  </div>
                </div>
                <div className={'body-top-end'}>
                  <div className={'option-wrapper'}>
                    <div className={'option-title'}>公司标签</div>
                    <FormItem>{
                      getFieldDecorator('Tags')(
                        <input className={'option-input'}
                               type={'text'}/>
                      )
                    }</FormItem>
                  </div>
                </div>
              </div>

              <div className={'body-middle'}>
                <div className={'title-wrapper'}>
                  <span className={'title-bar'}/>
                  <span className={'title-text'}>企业简介</span>
                  <Button className={'title-btn-save'} buttonType={'submit'} onClick={() => {
                  }}>保存</Button>
                </div>
                <FormItem>{
                  getFieldDecorator('Introduce', {initialValue: companyData.Introduce})(
                    <textarea className={'company-intro'}/>
                  )
                }</FormItem>
                <div className={'title-wrapper'}>
                  <span className={'title-bar'}/>
                  <span className={'title-text'}>企业风景</span>
                  <Button className={'title-btn-more'} buttonType={"button"} onClick={() => {
                    if (sightsData && sightsData.length > 0) {
                      this.setState({showCheckbox: !showCheckbox})
                    }
                  }}>更多</Button>
                  <Button className={'title-btn-save'}
                          buttonType={'button'}
                          onClick={() => {

                            if (showCheckbox) {
                              let data = []
                              sightsData.map(function (item, index) {
                                if (!item.checked)
                                  return data.push(item)
                              })
                              if (data.length === 0) {
                                this.setState({showCheckbox: false, sightsData: data})
                              } else {
                                this.setState({sightsData: data})
                              }
                            } else {
                              this.uploadSightsFiles(0)
                            }
                          }}>{showCheckbox ? '删除' : '保存'}</Button>
                </div>
                <div className={'sights-wrapper'}>
                  <ul className={'sights-ul'}>
                    {
                      sightsData && sightsData.map(function (item, index) {
                        return <li className={'sights-li'}>
                          {showCheckbox && <Checkbox className={'sights-check-box'} value={index} checked={item.checked}
                                                     onChange={(e) => {
                                                       let index = parseInt(e.target.value)
                                                       let data = sightsData.map(function (i, d) {
                                                         return d === index ? Object.assign(i, {checked: e.target.checked}) : i
                                                       })
                                                       self.setState({sightsData: Object.assign(sightsData, data)})
                                                     }
                                                     }/>}
                          <img className={'sights-img'} src={typeof item.pic === 'string' ?
                            `${appConfig.apiHost}/File/?pid=${item.pic}&key=${store.get(USER_KEY)}` :
                            item.preview} alt={'Opps!'}/>
                        </li>
                      })
                    }
                  </ul>
                  <Dropzone className={'image-drop-zone'}
                            onDrop={this.handleSightsFileSelect.bind(this)}
                            action={'http://101.201.51.208:9528/File'}
                            accept={'image/*'}
                            multiple={false}>
                    <div className={'default-wrapper'}>
                      <img className={'image-default'} src={icons.uploadImg}/>
                      <span>点击添加图片</span>
                    </div>
                  </Dropzone>
                </div>
              </div>
            </Form>
            <div className={'body-end'} style={{height: '25rem'}}>
              <div className={'title-wrapper'}>
                <span className={'title-bar'}/>
                <span className={'title-text'}>招聘岗位</span>
                <Button className={'title-btn-more'} onClick={() => {
                  this.props.router.push({
                    pathname: 'home/add/job',
                    query: {Id: -1},
                    state: {
                      companyId: companyData.Id,
                      area: companyData.Area,
                      revise: false,
                    }
                  })
                }}>添加</Button>
                <Button className={'title-btn-save'} onClick={() => {
                  this.props.router.push({
                    pathname: 'home/revise/job',
                    query: {Id: 1},
                    state: {
                      companyId: companyData.Id,
                      area: companyData.Area,
                      revise: false,
                    }
                  })
                }}>删除</Button>
              </div>
              <AntTable columns={columns} data={JobData} rowSelection={rowSelection}
                        pagination={true} currentPage={currentPage} pageSize={pageSize}
                        onChange={(pagination) => {
                          this.setState({
                            currentPage: pagination.current,
                            pageSize: pagination.pageSize,
                          })
                        }}
              />
            </div>
          </div>
        </div>
    )
  }
}

module.exports = Form.create()(withRouter(ReviseCompany))
